import { messageMap } from './message';
import * as vscode from 'vscode';


export default class YapiWebviewProvider implements vscode.WebviewViewProvider {

  public static readonly viewType = 'zd.yapi';

  private _view?: vscode.WebviewView;


  constructor(
		private readonly _extensionUri: vscode.Uri,
  ) { }

  public resolveWebviewView(
    webviewView: vscode.WebviewView,
    _context: vscode.WebviewViewResolveContext,
    _token: vscode.CancellationToken,
  ) {
    this._view = webviewView;

    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [
        this._extensionUri,
      ],
    };

    webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

    webviewView.webview.onDidReceiveMessage(data => {
      const { type, payload } = data;
      const typeName = type.split('__')[0];

      messageMap[typeName]?.({
        webviewView,
        originalType: type,
      }, payload);
    });
  }

  private _getHtmlForWebview(webview: vscode.Webview) {
    const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'dist/ui', 'yapi.js'));

    return `<!DOCTYPE html>
			<html lang="en">
			<head>
				<meta charset="UTF-8">
			</head>
			<body>
                <div id="app"></div>
				<script src="${scriptUri}"></script>
			</body>
        </html>`;
  }
}